﻿using BLL;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Data;
using System.IO;
using NPOI;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace LandAppraisal.Controllers
{
    public class ProspectingController : ApiController
    {
        AdminBLL adminbll = new AdminBLL();
        EmployeeBLL employeebll = new EmployeeBLL();

        #region 勘查列表的展示
        /// <summary>
        /// 勘查列表的展示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string GetProspectingList(string Survey)
        {
            var list = adminbll.RegisterList();
            if (Survey == "请选择")
            {
                return JsonConvert.SerializeObject(list);
            }
            else
            {
                return JsonConvert.SerializeObject(list.Where(p => p.Survey == Survey));
            }
        }
        #endregion

        #region 询价列表展示
        /// <summary>
        /// 询价列表展示
        /// </summary>
        /// <returns></returns>
        public string GetEAInquiry()
        {
            return JsonConvert.SerializeObject(adminbll.GetList<EAInquiry>());
        }
        #endregion

        #region 修改项目状态为已勘察
        /// <summary>
        /// 修改项目状态为已勘察
        /// </summary>
        /// <returns></returns>
        public int UpdateState(string ProjectNumberber)
        {
            return adminbll.UpdateState(ProjectNumberber);
        }
        #endregion

        #region 上传图片
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="ims"></param>
        /// <returns></returns>
        [HttpPost]
        public string Post(EAPhoto photo)
        {
            //获取图片二进制流
            string base64str = photo.Photo_Url.Split(',')[1];
            //把二进制流转换成字节流
            byte[] data = Convert.FromBase64String(base64str);
            //路径
            string Photo_Name = DateTime.Now.ToString("yyyyMMddhhmmsss") + "." + "jpg";
            string strflie = AppDomain.CurrentDomain.BaseDirectory + "Images\\";
            strflie += Photo_Name;
            //写入流
            using (Stream f = new FileStream(strflie, FileMode.Create))
            {
                f.Write(data, 0, data.Length);
                f.Close();
            }
            return "/Images/" + Photo_Name;
        }
        #endregion

        #region 勘查列表详情反填
        /// <summary>
        /// 勘查列表详情反填
        /// </summary>
        /// <param name="pnum"></param>
        /// <returns></returns>
        [HttpGet]
        public string BackData(string ProjectNumber)
        {
            return JsonConvert.SerializeObject(employeebll.BackDatas(ProjectNumber));
        }
        #endregion

        #region 上传Excel文件
        /// <summary>
        /// 上传Excel文件
        /// </summary>
        /// <param name="ims"></param>
        /// <returns>返回excel中的数据（json格式）</returns>
        [HttpPost]
        public string ExcelFileUp(Excel excel)
        {
            string base64str = excel.ExcelURL.Split(',')[1];
            //把二进制流转换成字节流
            byte[] data = Convert.FromBase64String(base64str);
            //路径
            string ExcelName = DateTime.Now.ToString("yyyyMMddhhmmsss") + "." + "xls";
            string strflie = AppDomain.CurrentDomain.BaseDirectory + "Excel\\";
            strflie += ExcelName;
            //写入流
            using (Stream f = new FileStream(strflie, FileMode.Create))
            {
                f.Write(data, 0, data.Length);
                f.Close();
            }
            DataTable table = ImportExcel(strflie);

            return JsonConvert.SerializeObject(table);
        }
        /// 获取excel内容
        /// </summary>
        /// <param name="filePath">excel文件路径</param>
        /// <returns></returns>
        public static DataTable ImportExcel(string filePath)
        {
            DataTable dt = new DataTable();
            using (FileStream fsRead = System.IO.File.OpenRead(filePath))
            {
                IWorkbook wk = null;
                //获取后缀名
                string extension = filePath.Substring(filePath.LastIndexOf(".")).ToString().ToLower();
                wk = new HSSFWorkbook(fsRead);
                //获取第一个sheet
                ISheet sheet = wk.GetSheetAt(0);
                //获取第一行
                IRow headrow = sheet.GetRow(0);
                //创建列
                for (int i = headrow.FirstCellNum; i < headrow.Cells.Count; i++)
                {
                    //  DataColumn datacolum = new DataColumn(headrow.GetCell(i).StringCellValue);
                    DataColumn datacolum = new DataColumn("F" + (i + 1));
                    dt.Columns.Add(datacolum);
                }
                //读取每行,从第二行起
                for (int r = 1; r <= sheet.LastRowNum; r++)
                {
                    bool result = false;
                    DataRow dr = dt.NewRow();
                    //获取当前行
                    IRow row = sheet.GetRow(r);
                    //读取每列
                    for (int j = 0; j < row.Cells.Count; j++)
                    {
                        ICell cell = row.GetCell(j); //一个单元格
                        dr[j] = GetCellValue(cell); //获取单元格的值
                        //全为空则不取
                        if (dr[j].ToString() != "")
                        {
                            result = true;
                        }
                    }
                    if (result == true)
                    {
                        dt.Rows.Add(dr); //把每行追加到DataTable
                    }
                }
            }
            return dt;
        }
        private static string GetCellValue(ICell cell)
        {
            if (cell == null)
                return string.Empty;
            switch (cell.CellType)
            {
                case CellType.Blank: //空数据类型 这里类型注意一下，不同版本NPOI大小写可能不一样,有的版本是Blank（首字母大写)
                    return string.Empty;
                case CellType.Boolean: //bool类型
                    return cell.BooleanCellValue.ToString();
                case CellType.Error:
                    return cell.ErrorCellValue.ToString();
                case CellType.Numeric: //数字类型
                    if (HSSFDateUtil.IsCellDateFormatted(cell))//日期类型
                    {
                        return cell.DateCellValue.ToString();
                    }
                    else //其它数字
                    {
                        return cell.NumericCellValue.ToString();
                    }
                case CellType.Unknown: //无法识别类型
                default: //默认类型
                    return cell.ToString();//
                case CellType.String: //string 类型
                    return cell.StringCellValue;
                case CellType.Formula: //带公式类型
                    try
                    {
                        HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                        e.EvaluateInCell(cell);
                        return cell.ToString();
                    }
                    catch
                    {
                        return cell.NumericCellValue.ToString();
                    }
            }
        }
        #endregion

        #region 提交评估信息
        /// <summary>
        /// 提交评估信息
        /// </summary>
        /// <returns></returns>
        public int SubmitAssessment(EABasic_Info eabasic)
        {
            eabasic.Basic_Excl = eabasic.Basic_Excl.Split(',')[1];
            eabasic.Basic_Enclosure = eabasic.Basic_Enclosure.Split(',')[1];
            if (adminbll.UpdateState(eabasic) > 0)
            {
                return 1;//修改成功
            }
            return 0;//修改失败
        }
        #endregion

    }
}
